<?php
/**
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;



use app\common\func\Func;
use library\Controller;
use think\Db;

class Auth extends Controller
{
    /**
     * 获取小程序配置
     * @return array
     */
    private function config()
    {
        return config('wechat.miniapp');
    }
    public function index()
    {
        try {
            $code = $this->request->param('code');
            $result = \We::WeMiniCrypt($this->config())->session($code);
            if (isset($result['openid'])) {
                data_save('StoreMember', ['openid' => $result['openid']], 'openid');
                $token = Func::jwtGetToken($result);
                //增加积分
                $this->addScore($result['openid']);
                $this->success('授权CODE信息换取成功！', $token);
            }
            $this->error("[{$result['errcode']}] {$result['errmsg']}");
        } catch (\think\exception\HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->error("授权CODE信息换取失败，{$exception->getMessage()}");
        }
   }

    public function refreshToken()
    {
        if(!empty($this->request->param('refresh_token'))){
            $token = $this->request->param('refresh_token');
            try{
                $data = Func::jwtDecodeToken($token)->data;
            }catch (\Exception $exception){
                if('Expired token' == $exception->getMessage()){
                    $this->error('请删除或者退出小程序,重新打开!', [], -199);
                }
            }
            //重新刷新
            if($data){
                $token = Func::jwtGetToken($data, true);
                $this->success('刷新token成功！', $token);
            }else{
                $this->error('刷新token失败!', [], -199);
            }
        }
    }

    public function addScore($openId)
    {
        $type = 1;
        if($type == 1){
            $dayStart = date("Y-m-d"). " 00:00:00";
            $dayEnd = date("Y-m-d"). " 23:59:59";
            $times = Db::table('lite_member_score_record')->where([
                'open_id' => $openId,
            ])->whereBetween("create_time", [$dayStart, $dayEnd])->count();
            if($times < 5){
                Func::addScoreLocal($type, $openId);
            }
        }
    }
}